package cn.tedu.csmall.passport.service.impl;

import cn.tedu.csmall.passport.ex.ServiceException;
import cn.tedu.csmall.passport.pojo.dto.AdminAddNewDTO;
import cn.tedu.csmall.passport.pojo.dto.AdminLoginDTO;
import cn.tedu.csmall.passport.pojo.dto.AdminUpdateDTO;
import cn.tedu.csmall.passport.security.AdminDetails;
import cn.tedu.csmall.passport.web.ServiceCode;
import cn.tedu.csmall.passport.pojo.entity.Admin;
import cn.tedu.csmall.passport.mapper.AdminMapper;
import cn.tedu.csmall.passport.service.IAdminService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 管理员 服务实现类
 * </p>
 *
 * @author xBest
 * @since 2023-04-01
 */

@Service
@Slf4j
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements IAdminService {

    @Autowired
    AdminMapper adminMapper;

    @Autowired
    private AuthenticationManager authenticationManager;
    @Override
    public String login(AdminLoginDTO adminLoginDTO) {
        log.debug("开始处理【管理员登录】的业务，参数：{}", adminLoginDTO);

        // 创建认证信息对象
        Authentication authentication = new UsernamePasswordAuthenticationToken(
                adminLoginDTO.getUsername(), adminLoginDTO.getPassword());
        // 调用认证管理器执行认证
        authenticationManager.authenticate(authentication);
        // 如果没有出现异常，则表示验证登录成功
        Authentication authenticationResult
                = authenticationManager.authenticate(authentication);
        // 如果没有出现异常，则表示验证登录成功，需要将认证信息存入到Security上下文
//        log.debug("验证登录成功，即将向SecurityContext中存入Authentication");
//        SecurityContext securityContext = SecurityContextHolder.getContext();
//        securityContext.setAuthentication(authenticationResult);
        Object principal = authenticationResult.getPrincipal();
        AdminDetails adminDetails = (AdminDetails) principal;
        Map<String, Object> claims = new HashMap<>();
        claims.put("id", adminDetails.getId());
        claims.put("username", adminDetails.getUsername());

        String secretKey = "S2anH27hslHGPR76GBabsd087BANSD1v";
        Date exp = new Date(System.currentTimeMillis() + 15 * 24 * 60 * 60 * 1000);
        String jwt = Jwts.builder()
                // Header（头部信息）：声明算法与Token的类型
                .setHeaderParam("alg", "HS256")
                .setHeaderParam("typ", "JWT")
                // Payload（载荷）：数据，表现为Claims
                .setClaims(claims)
                .setExpiration(exp)
                // Signature：验证签名
                .signWith(SignatureAlgorithm.HS256, secretKey)
                // 完成
                .compact();
        log.debug(jwt);

        return jwt;
    }

    @Override
    public void addNew(AdminAddNewDTO adminAddNewDTO) {
        int rows = adminMapper.countByName(adminAddNewDTO.getUsername());
        if (rows != 0) {
            String message = "添加用户失败！用户名已被占用";
            throw new ServiceException(ServiceCode.ERR_CONFLICT,message);
        }
        Admin admin = new Admin();
        BeanUtils.copyProperties(adminAddNewDTO,admin);
        int result = adminMapper.insert(admin);
        if (result !=1) {
            String message = "添加用户失败";
            throw new ServiceException(ServiceCode.ERR_INSERT,message);
        }
    }

    @Override
    public void delete(Long id) {
        int rows = adminMapper.countById(id);
        if (rows == 0) {
            String message = "删除用户失败，该用户不存在";
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }
        rows = adminMapper.deleteById(id);
        if (rows != 1) {
            String message = "删除用户失败，服务器忙，请稍后再尝试！";
            throw new ServiceException(ServiceCode.ERR_DELETE, message);
        }
    }

    @Override
    public void update(AdminUpdateDTO adminUpdateDTO) {
        int rows = adminMapper.countById(adminUpdateDTO.getId());
        if (rows == 0) {
            String message = "更新用户失败，该用户不存在";
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }
        Admin admin = new Admin();
        BeanUtils.copyProperties(adminUpdateDTO,admin);
        rows = adminMapper.update(admin);
        if (rows != 1) {
            String message = "更新用户失败！";
            throw new ServiceException(ServiceCode.ERR_UPDATE, message);
        }
    }

    @Override
    public long count() {
        long queryResult = adminMapper.count();
        return queryResult;
    }
}
